Function Write-Log(){
	param(
		[Parameter(Mandatory=$true)]
		[ValidateSet("Warning", "Error", "Success","Normal")]
		$logType,
		[Parameter(Mandatory=$true)]
		$logInfo,
		[Parameter(Mandatory=$true)]
		$logfile
	)
	switch($logType){
		"Warning"{write-warning $logInfo}
		"Error"{write-error $logInfo}
		"Success"{write-host $logInfo}
		"Normal" {write-host $logInfo}
	}
	(get-date).tostring("yyyy-MM-dd hh:mm:ss")+"--"+$logType+": "+$logInfo >> $logfile
}
Function Open-IE($log){
	$ie=$null
	Foreach($i in (New-Object -ComObject Shell.Application).Windows()){If($i.Name -like "*Internet Explorer*"){ $ie=$i ; break}} #$ie.FullScreen=$true
	If( $ie -eq $null ){
		$start=get-date
		do{
			$error.clear()
			try{$ie=new-object -com InternetExplorer.Application
			}catch{
				$runningSeconds = ((get-date) -$start).TotalSeconds
				if($runningSeconds -gt 10){Write-Log -logType Error "Waiting too long(10s) for IE open" $log ; return $null}
			}finally{}
		}while($error.count -ne 0)
	}
	return $ie
}
$this_path = Split-Path -Parent ($MyInvocation.MyCommand.Definition)
$log="$this_path\$((Get-Date).ToString('yyyyMMdd_HHmmss')).log"
$user=$env:username
Do{
	$credentials = Get-Credential -UserName $user -Message "Please enter password as it was empty!"
	If( $credentials -ne $null ){
		$user=$credentials.GetNetworkCredential().username
		$passwd = $credentials.GetNetworkCredential().Password
	}else{return}
}While( $passwd -eq $null -or [string]::IsNullOrWhiteSpace($passwd.trim()))
Do{
    Try{[ADSI]::Exists("WinNT://nam/$user,user") 1>$null 2>&1;$rst=$true}Catch{$user=read-host "$user not exists in AD, please re-enter it";$rst=$false}Finally{}
}While( !$rst )
$cc_url_list=@(
	'PROD=http://isg/control-central/',
	'UAT=http://isg-uat/control-central/',
	'DEV=http://isg-dev/control-central',
	'SIT=http://isg-sit/control-central/'
)
If(($ie=Open-IE $log) -ne $null){
	$results=@();$cc_cnt=1
	$results+="`"DOMAIN`",`"ENV`",`"VDI`",`"FID`""
	Foreach( $list in $cc_url_list[0,1]){ # loop prod and uat cc
		$domain,$url=$list.split('=')
		write-host "$cc_cnt-Navigating $domain control center: $url ..."
		$ie.Navigate($url) ; while ($ie.Busy -or $ie.ReadyState -ne 4) { Start-Sleep -Milliseconds 200} # go to the cc webpage
		write-host "$cc_cnt-Logginging $domain control center..."
		If(($userEle=($ie.Document.IHTMLDocument3_getElementByID("usernameinput"))) -ne $null){ # log in the cc
			Try{$userEle.value=$user}Catch{ $ie.Quit()}Finally{}
			Foreach( $inputValue in ($ie.Document.IHTMLDocument3_getElementsByTagName("input"))){
				Try{
					if($inputValue.name -eq "j_password"){$inputValue.value=$passwd;break}
				}Catch{
				    $ie.Quit()
				}Finally{}
			}
			Foreach( $button in ($ie.Document.IHTMLDocument3_getElementsByTagName("button"))){
				Try{
					If( $button.innertext -eq "Login"){$button.click();break}
				}Catch{
				    $ie.Quit()
				}Finally{}
			}
			while ($ie.Busy -or $ie.ReadyState -ne 4) { Start-Sleep -Milliseconds 200}
		}
		write-host "$cc_cnt-Waiting $domain control center webpage fully loaded..."
		$cnt=0
		Do{ # loop until cc webpage fully loaded
			$is_page_fully_loaded=$false
			Foreach( $span in ($ie.Document.IHTMLDocument3_getElementsByTagName("span"))){
				If( $span.innertext -imatch "NAM|APAC|EMEA" ){$is_page_fully_loaded=$true;break}
			}
			$cnt++ ; start-sleep -Seconds 1
			If( $cnt -gt 100 ){
				Write-Log -logType Error "Waiting too long(100s) for control center loading" $log ; ii $log;break
			}
		}While( !$is_page_fully_loaded )
		If( !$is_page_fully_loaded ){continue} # go to next cc url if this one cannot be loaded
		write-host "$cc_cnt-Trying to get mapped vdi-user from $domain control center..."
		Foreach( $span in ($ie.Document.IHTMLDocument3_getElementsByTagName("span"))){
			If( $span.classname -eq "ng-binding" ){
				$env=Switch -regex ($span.innertext){
					"nam"{"NAM";break}
					"apac"{"APAC";break}
					"emea"{"EMEA";break}
				}
				If( $env -in "NAM","APAC","EMEA" ){
					Foreach( $vdi_user in ($span.parentNode.parentNode.innerHTML.Split('>').split('<') -imatch "\(.{7}\)")){
						$vdi,$user=($vdi_user.Split('(').split(')'))[0,1].Trim()
						$results+="`"$domain`",`"$env`",`"$vdi`",`"$user`""
					}
				}
			}
		}
	}
	$results|out-file -FilePath "$this_path\cc_vdi_user.csv" -Encoding utf8 -Force
	write-host "$cc_cnt-Done getting mapped vdi-user from $domain control center..."
	write-host -ForegroundColor Yellow "The result csv file has been saved in '$this_path\cc_vdi_user.csv'"
	$ie.Quit() # close IE brower
}
